import React from "react";
import FieldView from "./field/View";
import FieldError from "./field/Error";
import FBHeaderView from "../component/form-header/View";
import FBFooterView from "../component/form-footer/View";
import {viewTypes} from "../../../../constants/form";
import "./Main.less";
import {Consumer} from "../theme";

export default class FormMainView extends React.Component {
  constructor() {
    super();

    this.onValueChange = _.memoize(this.onValueChange.bind(this));
  }

  onValueChange(uuid) {
    return value => this.props.onValueChange(uuid, value);
  }

  getFieldView(com) {
    const { viewType, onValueChange, toggleFooterDisable } = this.props;

    if (com.config.complex) {
      return (
        <FieldView 
          key={com.uuid}
          viewType={viewType}
          field={com}
          onChange={onValueChange}
        />
      );
    }

    return (
      <FieldView 
        key={com.uuid}
        viewType={viewType}
        field={com}
        onChange={this.onValueChange(com.uuid)}
        toggleFooterDisable={toggleFooterDisable}
      />
    );
  }

  render() {
    const { formHeader, formFooter, components, onSubmit, shortkey } = this.props;

    if (!components) return null;

    return (
      <Consumer>
        {({form}) => (
          <div className='wea-edc-fv-main' style={Object.assign(form.css, form.border.css)}>
            <FBHeaderView data={formHeader.config} />
            {
              form.divider.visible ?
                <div style={{borderBottom: '1px solid '+ form.divider.color}}/>
                : null
            }
            <div className='wea-edc-fv-body clearfix'>
              {components.filter(com => !com.pid).map(com => (
                !com.visible ? null :
                  <FieldError key={com.uuid} error={com.errorCom ? com.errorCom.error : com.error} >
                    {this.getFieldView(com)}
                  </FieldError>
              ))}
            </div>
            {
              form.divider.visible ?
                <div style={{borderBottom: '1px solid '+ form.divider.color}}/>
                : null
            }
            <FBFooterView
              data={formFooter.config}
              loading={formFooter.loading}
              disable={formFooter.disable}
              onSubmit={onSubmit}
            />
          </div>
          )}
      </Consumer>
    );
  }
}

FormMainView.defaultProps = {
  formHeader: null,
  formFooter: null,
  components: null,
  wrapperDOM: document.body,
  viewType: viewTypes.PC,
  onSubmit: () => { },
  onValueChange: () => { }
};